<template>
  <div class="water-meter">
    <!-- 左侧树形结构区域 -->
    <div class="left-tree-panel">
      <div class="tree-header">
        <h4>
          <i class="el-icon-office-building"></i>
          楼栋用房分类
        </h4>
      </div>
      <div class="tree-search">
        <el-input 
          v-model="treeSearchText" 
          placeholder="请输入楼栋内容" 
          size="small" 
          clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      <div class="tree-container">
        <el-tree
          :data="treeData"
          :props="treeProps"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          :expand-on-click-node="false"
          :default-expand-all="true"
          :highlight-current="true"
          @node-click="handleNodeClick"
          class="custom-tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="tree-node-label">
              <i :class="getNodeIcon(data)" class="tree-node-icon"></i>
              {{ node.label }}
            </span>
          </span>
        </el-tree>
      </div>
    </div>
    
    <!-- 右侧内容区域 -->
    <div class="right-content-panel">
      <!-- 操作按钮区 -->
      <div class="action-container">
        <div class="action-left">
          <div class="action-buttons">
            <el-button type="primary" icon="el-icon-lightning" @click="batchOperation('switch')">拉闸</el-button>
            <el-button type="success" icon="el-icon-check" @click="batchOperation('close')">合闸</el-button>
            <el-button type="warning" icon="el-icon-refresh" @click="batchOperation('replace')">换表</el-button>
          </div>
          <span class="selected-info" v-if="selectedNode">
            当前选择: {{ selectedNode.label }}
          </span>
        </div>
        <div class="action-right">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入房间号或用户名"
            size="small"
            clearable
            style="width: 200px; margin-right: 10px;"
            @keyup.enter.native="handleSearch">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
          <el-button size="small" @click="resetSearch">重置</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <div class="table-header">
          <div class="table-title">
            <i class="el-icon-tickets"></i>
            水表列表
          </div>
          <div class="table-info">
            共 {{ total }} 条，每页 {{ pageSize }} 条
          </div>
        </div>
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          :header-cell-style="headerCellStyle"
          class="custom-table"
          v-loading="loading"
          element-loading-text="加载中..."
        >
          <el-table-column prop="roomNumber" label="房间号" width="120" align="center">
            <template slot-scope="scope">
              <el-tag size="small" type="info">{{ scope.row.roomNumber }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="用户名" width="120" align="center">
            <template slot-scope="scope">
              <div class="user-info">
                <i class="el-icon-user"></i>
                {{ scope.row.userId }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="meterMode" label="水表模式" width="120" align="center">
            <template slot-scope="scope">
              <el-tag 
                size="small" 
                type="primary"
              >
                {{ scope.row.meterMode }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="mergeStatus" label="合闸状态" width="120" align="center">
            <template slot-scope="scope">
              <el-tag 
                size="small" 
                :type="scope.row.mergeStatus === '合闸' ? 'success' : 'danger'"
              >
                {{ scope.row.mergeStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="meterStatus" label="水表状态" width="120" align="center">
            <template slot-scope="scope">
              <el-tag 
                size="small" 
                :type="scope.row.meterStatus === '在线' ? 'success' : 'warning'"
              >
                {{ scope.row.meterStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button 
                type="primary" 
                size="mini" 
                icon="el-icon-lightning"
                class="action-btn"
                @click="operateMeter(scope.row, 'switch')"
              >
                拉闸
              </el-button>
              <el-button 
                type="success" 
                size="mini" 
                icon="el-icon-check"
                class="action-btn"
                @click="operateMeter(scope.row, 'close')"
              >
                合闸
              </el-button>
              <el-button 
                type="warning" 
                size="mini" 
                icon="el-icon-refresh"
                class="action-btn"
                @click="operateMeter(scope.row, 'replace')"
              >
                换表
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="mt-4"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 操作确认弹窗 -->
    <el-dialog
      :title="operationDialog.title"
      :visible.sync="showOperationDialog"
      width="500px"
      class="custom-dialog"
      :close-on-click-modal="false"
    >
      <div class="operation-content">
        <div class="operation-info">
          <div class="meter-info">
            <p><strong>房间号:</strong> {{ selectedMeter ? selectedMeter.roomNumber : '' }}</p>
            <p><strong>用户名:</strong> {{ selectedMeter ? selectedMeter.userId : '' }}</p>
            <p><strong>水表模式:</strong> {{ selectedMeter ? selectedMeter.meterMode : '' }}</p>
            <p><strong>当前状态:</strong> 
              <el-tag 
                size="small" 
                :type="selectedMeter && selectedMeter.mergeStatus === '合闸' ? 'success' : 'danger'"
              >
                {{ selectedMeter ? selectedMeter.mergeStatus : '' }}
              </el-tag>
            </p>
          </div>
        </div>
        <div class="operation-warning" v-if="operationDialog.type === 'switch'">
          <el-alert
            title="警告：拉闸操作将断开水表供水，请确认操作！"
            type="warning"
            :closable="false"
            show-icon
          >
          </el-alert>
        </div>
        <div class="operation-warning" v-if="operationDialog.type === 'replace'">
          <el-alert
            title="注意：换表操作将更换水表设备，请确认操作！"
            type="info"
            :closable="false"
            show-icon
          >
          </el-alert>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showOperationDialog = false">取消</el-button>
        <el-button 
          :type="getOperationButtonType()"
          @click="confirmOperation"
          :loading="operating"
        >
          {{ operating ? '操作中...' : '确认' + operationDialog.title }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import meterManagementMock from '@/api/mock/meterManagement'
export default {
  name: 'WaterMeter',
  data () {
    return {
      loading: false,
      operating: false,
      tableData: [],
      allData: [],
      filteredData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      showOperationDialog: false,
      selectedMeter: null,
      selectedNode: null,
      operationDialog: {
        title: '',
        type: ''
      },
      searchForm: {
        keyword: ''
      },
      headerCellStyle: {
        backgroundColor: '#f5f7fa',
        color: '#333',
        fontWeight: 'bold',
        textAlign: 'center'
      },
      // 树形结构相关数据
      treeSearchText: '',
      treeData: [
        {
          id: 'root',
          label: '楼栋用房分类',
          type: 'root',
          children: [
            {
              id: 'dormitory',
              label: '宿舍',
              type: 'building',
              children: [
                {
                  id: 'building_a',
                  label: 'A栋',
                  type: 'floor',
                  children: [
                    { id: 'room_101', label: '101', type: 'room' },
                    { id: 'room_102', label: '102', type: 'room' },
                    { id: 'room_103', label: '103', type: 'room' },
                    { id: 'room_104', label: '104', type: 'room' }
                  ]
                }
              ]
            },
            {
              id: 'second_floor',
              label: '二层',
              type: 'building',
              children: [
                {
                  id: 'building_b',
                  label: 'B栋',
                  type: 'floor',
                  children: [
                    { id: 'room_201', label: '201', type: 'room' },
                    { id: 'room_202', label: '202', type: 'room' },
                    { id: 'room_203', label: '203', type: 'room' }
                  ]
                }
              ]
            }
          ]
        }
      ],
      treeProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    treeSearchText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    loadData() {
      this.loading = true
      this.allData = meterManagementMock.water.msg.list
      this.filteredData = [...this.allData]
      this.updateTableData()
      this.loading = false
    },
    updateTableData() {
      this.total = this.filteredData.length
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.tableData = this.filteredData.slice(start, end)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.updateTableData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.updateTableData()
    },
    // 树形结构相关方法
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getNodeIcon(data) {
      const iconMap = {
        'root': 'el-icon-office-building',
        'building': 'el-icon-house',
        'floor': 'el-icon-menu',
        'room': 'el-icon-location'
      }
      return iconMap[data.type] || 'el-icon-folder'
    },
    handleNodeClick(data) {
      this.selectedNode = data
      this.currentPage = 1
      
      if (data.type === 'room') {
        // 根据房间号过滤数据
        this.filteredData = this.allData.filter(item => 
          item.roomNumber === data.label
        )
      } else if (data.type === 'floor') {
        // 根据楼栋过滤数据
        const roomNumbers = this.getRoomNumbersByFloor(data)
        this.filteredData = this.allData.filter(item => 
          roomNumbers.includes(item.roomNumber)
        )
      } else if (data.type === 'building') {
        // 根据建筑过滤数据
        const roomNumbers = this.getRoomNumbersByBuilding(data)
        this.filteredData = this.allData.filter(item => 
          roomNumbers.includes(item.roomNumber)
        )
      } else {
        // 显示所有数据
        this.filteredData = [...this.allData]
      }
      
      this.updateTableData()
    },
    getRoomNumbersByFloor(floorData) {
      const roomNumbers = []
      if (floorData.children) {
        floorData.children.forEach(room => {
          if (room.type === 'room') {
            roomNumbers.push(room.label)
          }
        })
      }
      return roomNumbers
    },
    getRoomNumbersByBuilding(buildingData) {
      const roomNumbers = []
      if (buildingData.children) {
        buildingData.children.forEach(floor => {
          if (floor.children) {
            floor.children.forEach(room => {
              if (room.type === 'room') {
                roomNumbers.push(room.label)
              }
            })
          }
        })
      }
      return roomNumbers
    },
    // 搜索相关方法
    handleSearch() {
      this.currentPage = 1
      if (!this.searchForm.keyword.trim()) {
        this.filteredData = [...this.allData]
      } else {
        this.filteredData = this.allData.filter(item => 
          item.roomNumber.includes(this.searchForm.keyword) ||
          item.userId.includes(this.searchForm.keyword)
        )
      }
      this.updateTableData()
    },
    resetSearch() {
      this.searchForm.keyword = ''
      this.selectedNode = null
      this.filteredData = [...this.allData]
      this.currentPage = 1
      this.updateTableData()
      this.$refs.tree.setCurrentKey(null)
    },
    // 批量操作
    batchOperation(operation) {
      const operationMap = {
        'switch': '拉闸',
        'close': '合闸',
        'replace': '换表'
      }
      this.$message.success(`批量${operationMap[operation]}操作`)
    },
    // 单个操作
    operateMeter(meter, operation) {
      this.selectedMeter = meter
      const operationMap = {
        'switch': { title: '拉闸', type: 'switch' },
        'close': { title: '合闸', type: 'close' },
        'replace': { title: '换表', type: 'replace' }
      }
      this.operationDialog = operationMap[operation]
      this.showOperationDialog = true
    },
    getOperationButtonType() {
      const typeMap = {
        'switch': 'danger',
        'close': 'success',
        'replace': 'warning'
      }
      return typeMap[this.operationDialog.type] || 'primary'
    },
    confirmOperation() {
      this.operating = true
      setTimeout(() => {
        // 更新表格数据
        if (this.selectedMeter) {
          if (this.operationDialog.type === 'switch') {
            this.selectedMeter.mergeStatus = '拉闸'
          } else if (this.operationDialog.type === 'close') {
            this.selectedMeter.mergeStatus = '合闸'
          } else if (this.operationDialog.type === 'replace') {
            this.$message.success('换表操作完成，请联系技术人员进行设备更换')
          }
        }
        this.$message.success(this.operationDialog.title + '操作成功')
        this.operating = false
        this.showOperationDialog = false
      }, 1500)
    }
  }
}
</script>
<style scoped>
/* 主容器样式 */
.water-meter {
  display: flex;
  height: calc(100vh - 84px);
  background: #f5f7fa;
}

/* 左侧树形结构面板 */
.left-tree-panel {
  width: 280px;
  background: white;
  border-radius: 8px;
  margin-right: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.tree-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
  border-radius: 8px 8px 0 0;
}

.tree-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tree-header i {
  color: #409eff;
  font-size: 18px;
}

.tree-search {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.tree-container {
  flex: 1;
  padding: 8px;
  overflow-y: auto;
}

.custom-tree {
  background: transparent;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.tree-node-label {
  display: flex;
  align-items: center;
  gap: 6px;
}

.tree-node-icon {
  color: #409eff;
  font-size: 14px;
}

/* 右侧内容面板 */
.right-content-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 操作按钮区 */
.action-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  border-radius: 6px;
  font-weight: 500;
}

.selected-info {
  color: #606266;
  font-size: 14px;
  background: #f0f9ff;
  padding: 4px 12px;
  border-radius: 4px;
  border: 1px solid #b3d8ff;
}

.action-right {
  display: flex;
  align-items: center;
}

/* 表格容器 */
.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-title i {
  color: #3498db;
  font-size: 18px;
}

.table-info {
  color: #909399;
  font-size: 14px;
}

.custom-table {
  flex: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.user-info i {
  color: #409eff;
  font-size: 14px;
}

/* 操作按钮样式 */
.action-btn {
  margin: 0 2px;
  border-radius: 4px;
  font-size: 12px;
  padding: 5px 8px;
}

/* mt-4 样式 */
.mt-4 {
  margin-top: 16px;
  padding: 0 20px 20px;
}

/* 统一蓝色表格行背景 */
.custom-table >>> .el-table__body tr {
  background-color: #4a5a7a !important;
}

.custom-table >>> .el-table__body tr:hover {
  background-color: #5a6a8a !important;
}

.custom-table >>> .el-table__body tr td {
  color: #ffffff !important;
}

/* 操作弹窗样式 */
.operation-content {
  padding: 20px;
}

.operation-info {
  margin-bottom: 20px;
}

.meter-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.meter-info p {
  margin: 8px 0;
  color: #2c3e50;
}

.operation-warning {
  margin: 20px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-tree-panel {
    width: 240px;
  }
}

@media (max-width: 768px) {
  .water-meter {
    flex-direction: column;
    height: auto;
    padding: 16px;
  }
  
  .left-tree-panel {
    width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
    height: 300px;
  }
  
  .action-container {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .action-left,
  .action-right {
    justify-content: center;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .table-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}
</style>
